package com.pioneer.fationservice.serviceinfos;

import java.util.HashMap;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Projection;
import com.baidu.mapapi.model.LatLng;
import com.pioneer.fationservice.R;
import com.pioneer.fationservice.commons.SystemData;
import com.pioneer.fationservice.commons.SystemHttpURL;
import com.pioneer.fationservice.entries.MapShopListEntry;
import com.pioneer.fationservice.entries.ShopMarkerInfoEntry;
import com.pioneer.fationservice.helpers.PhoneHelper;
import com.pioneer.fationservice.models.MapShopInfoModel;
import com.pioneer.fationservice.models.MapShopListModel;
import com.pioneer.fationservice.parsers.MapShopInfoParser;
import com.pioneer.fationservice.parsers.MapShopListParser;
import com.pioneer.fationservice.selfviews.ShopMarkerInfoDialog;

/**
 * 地图页面
 * @author Mrper
 *
 */
public class ServiceMapActivity extends FinalActivity {
	
	private MapView mMapView;//百度地图组件
    @ViewInject(id=R.id.activity_service_map_flContainer) private FrameLayout flContainer;//百度地图容器
    @ViewInject(id=R.id.activity_service_map_imgBack,click="onBackClick") private ImageView imgBack;//返回
    @ViewInject(id=R.id.activity_service_map_txtInfo) private TextView txtInfo;//说明信息
    
    private boolean isAdjustMap = false;//是否已经调整过一次地图了
    private float currentMapZoom = 16;//地图缩放级别，默认为16
    private BaiduMap mBaiduMap; //百度地图对象
    private LatLng mCurrentLatLng,//当前的地理坐标
    			   mCenterLatLng;//地图中心坐标
    public LocationClient mLocationClient;//定位服务器
    @SuppressLint("UseSparseArrays") 
    private HashMap<Integer,LatLng> shoplst = new HashMap<Integer,LatLng>();//商家ID列表集合
    private int scrWidth,scrHeight;//屏幕宽度和高度
    private int flag = 0;//商家类型
    
    /**
     * 组件的点击事件
     * @param v
     */
    public void onBackClick(View v){
		this.finish();
		overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }
    
    private BDLocationListener mBDLocationListener = new BDLocationListener() {//定位监听器
		@Override
		public void onReceiveLocation(BDLocation location) {
			if(location == null) return;
			mCurrentLatLng = new LatLng(location.getLatitude(),location.getLongitude());//获取当前我的地理位置
			showMyLocation(location);//显示自己当前的位置
//			if(!isAdjustMap){//已经调整过一次，不再做二次调整
//				isAdjustMap = true;
//				//mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(mCurrentLatLng,currentMapZoom));
//				//mCenterLatLng = mBaiduMap.getMapStatus().target;//获取地图中心
//			}
			System.out.println("当前地理位置是："+location.getAddrStr());
		}
	};
	
	/**
	 * 初始化定位服务器
	 */
	public void initLocCliet(){
		mLocationClient = new LocationClient(this);
        LocationClientOption locOption = new LocationClientOption();
        locOption.setCoorType("bd09ll");
        locOption.setIsNeedAddress(true);
        locOption.setOpenGps(true);
        locOption.setScanSpan(20*1000);
        locOption.setTimeOut(10*1000);
        mLocationClient.setLocOption(locOption);
        mLocationClient.registerLocationListener(mBDLocationListener);
        mLocationClient.requestLocation();
        mLocationClient.start();
	}
	
	/**
	 * 显示自己的位置
	 */
	private void showMyLocation(BDLocation location){
		try{
			// 开启定位图层  
			mBaiduMap.setMyLocationEnabled(true);  
			// 构造定位数据  
			MyLocationData locData = new MyLocationData.Builder()  
			    .accuracy(location.getRadius())  
			    // 此处设置开发者获取到的方向信息，顺时针0-360  
			    .direction(location.getDirection()).latitude(location.getLatitude())  
			    .longitude(location.getLongitude()).build();  
			// 设置定位数据  
			mBaiduMap.setMyLocationData(locData);  
			// 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）  
			BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory  
			    .fromResource(R.drawable.ic_shop_detail_map_flag);  
			MyLocationConfiguration config = new MyLocationConfiguration(LocationMode.NORMAL,
					true, mCurrentMarker);  
			mBaiduMap.setMyLocationConfigeration(config);  
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//在地图上显示标注物
	public void showMarker(LatLng point,Bundle data,int resId){
		//构建Marker图标  
		BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(resId);  
		//构建MarkerOption，用于在地图上添加Marker  
		MarkerOptions option = new MarkerOptions().position(point).icon(bitmap); 
		option.extraInfo(data);//添加数据
		//在地图上添加Marker，并显示  
		mBaiduMap.addOverlay(option);
	}
	
	/**
	 * 地图状态发送变化时调用
	 */
	private OnMapStatusChangeListener mapStatusChangeListener = new OnMapStatusChangeListener() {
		
		@Override
		public void onMapStatusChangeStart(MapStatus mapStatus) {
		}
		
		@Override
		public void onMapStatusChangeFinish(MapStatus mapStatus) {
			if(Math.abs(currentMapZoom-mapStatus.zoom)>0.0000001){//缩放级别发生了变化
				currentMapZoom = mapStatus.zoom;//设置当前的地图缩放等级
				requestMapShoplst(mapStatus.target);//请求周边的商家
				Toast.makeText(getApplicationContext(), "缩放等级发生了变化!",Toast.LENGTH_SHORT).show();
				return;//结束该方法
			}
			LatLng centerLoc = mapStatus.target;//获取地图中心坐标
			if(mCenterLatLng!=null && (Math.abs(mCenterLatLng.latitude - centerLoc.latitude) > 0.000001
					|| Math.abs(mCenterLatLng.longitude - centerLoc.longitude) >0.000001)){
				requestMapShoplst(mapStatus.target);//请求周边的商家
				Toast.makeText(getApplicationContext(), "地图中心坐标发生了变化!",Toast.LENGTH_SHORT).show();
			}
		}
		
		@Override
		public void onMapStatusChange(MapStatus mapStatus) {
		}
	};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_map);
        //获得屏幕尺寸
        DisplayMetrics dm = PhoneHelper.getScreenInfo(this);
        scrWidth = dm.widthPixels;
        scrHeight = dm.heightPixels;
        mCurrentLatLng = SystemData.myLatLng;//赋值当前的地理位置
        //初始化百度地图
        BaiduMapOptions mapOptions = new BaiduMapOptions();
        mapOptions.zoomControlsEnabled(false);
        mapOptions.compassEnabled(false);
        mMapView = new MapView(this, mapOptions);
        mMapView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
        		FrameLayout.LayoutParams.MATCH_PARENT));
        flContainer.addView(mMapView, 0);
        mBaiduMap = mMapView.getMap();//获取百度地图对象
        mBaiduMap.setOnMapStatusChangeListener(mapStatusChangeListener);//监听地图变化
        mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {//地图标注点击事件
			@Override
			public boolean onMarkerClick(Marker maker) {
				Toast.makeText(ServiceMapActivity.this, "Marker被点击！", Toast.LENGTH_SHORT).show();
				if(maker!=null){
					//获取商家的弹窗信息
					Bundle data = maker.getExtraInfo();
					if(data.containsKey("shopId")) 
						requestMapShopInfo(data.getInt("shopId"));
				}
				return true;
			}
		});
        initLocCliet();//初始化定位服务器
        initActivity();//初始化Activity
    }

    /***
     * 初始化Activity
     */
    public void initActivity(){
    	Intent intent = getIntent();
        if(intent!=null &&intent.hasExtra("shopId")){//显示该商家的地址
        	mCenterLatLng = new LatLng(intent.getDoubleExtra("latitude", 0),
        			intent.getDoubleExtra("longtitude", 0));
        	flag = intent.getIntExtra("flag", 0);//商家类型标识
        	int shopId = intent.getIntExtra("shopId", 0);//获取商家ID
        	shoplst.put(shopId,mCenterLatLng);//添加该商家到地图列表中
        	//在地图上标注商家
        	Bundle data = new Bundle();
        	data.putInt("shopId", shopId);
        	showMarker(mCenterLatLng,data,R.drawable.ic_shop_detail_map_flag);
        	//设置地图中心为该商家
        	mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(mCenterLatLng,currentMapZoom));
        	//显示该商家的提示框
        	View vInfo = View.inflate(this, R.layout.win_map_target_info, null);
        	((TextView)vInfo.findViewById(R.id.win_map_target_info_txtTip)).setText(intent.getStringExtra("shopName"));
        	mBaiduMap.showInfoWindow(new InfoWindow(vInfo, mCenterLatLng,null));
        	//延时请求该商家的周边商家
        	mMapView.postDelayed(new Runnable(){//延迟执行
				@Override
				public void run() {
					requestMapShoplst(mCenterLatLng);//请求周边的商家
				}
			},200);
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
    		imgBack.performClick();//模拟点击返回按钮
    		return true;
    	}
    	return super.onKeyDown(keyCode, event);
    }
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    
	/**
	 * 获取地图上商家的列表
	 * @param shopId
	 */
	public void requestMapShoplst(LatLng mTargetLatLng){
		//final ProgressDialog dialog = ProgressDialog.show(this, "", "请稍等...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	Projection pj = mBaiduMap.getProjection();
    	LatLng latLngA = pj.fromScreenLocation(new Point(0,0));
    	LatLng latLngB = pj.fromScreenLocation(new Point(scrWidth,0));
    	LatLng latLngC = pj.fromScreenLocation(new Point(scrWidth,scrHeight));
    	LatLng latLngD = pj.fromScreenLocation(new Point(0,scrHeight));
    	params.put("f", String.valueOf(flag));
    	params.put("a", latLngA.longitude + "-" + latLngA.latitude);
    	params.put("b", latLngB.longitude + "-" + latLngB.latitude);
    	params.put("c", latLngC.longitude + "-" + latLngC.latitude);
    	params.put("d", latLngD.longitude + "-" + latLngD.latitude);                  
    	params.put("z", mTargetLatLng.longitude + "-" + mTargetLatLng.latitude);
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_MAP_LIST, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
//    			if(dialog!=null) dialog.dismiss();
    			System.out.println("地图商家列表信息----错误信息："+strMsg);
    			Toast.makeText(ServiceMapActivity.this, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
//    			if(dialog!=null) dialog.dismiss();
    			System.out.println("地图商家列表信息----返回信息："+str);
    			MapShopListModel model = new MapShopListParser(str).getResponseObject();
    			switch(model.status){
    			case 1:
    				for(MapShopListEntry item : model.mapShoplst){
    					if(!shoplst.containsKey(item.shopId)){//查看是否已经添加该地图标注
    						shoplst.put(item.shopId,item.shopLatLng);
    						//在地图上标注商家
    						Bundle data = new Bundle();
    						data.putInt("shopId", item.shopId);
    						showMarker(item.shopLatLng,data,R.drawable.ic_shop_detail_map_flag);
    					}
    				}
    				txtInfo.setText("当前共有"+shoplst.size()+"家商家");
    				break;
    			case 0:
    				Toast.makeText(ServiceMapActivity.this, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
    		}
    	});
	}
    
	
	/**
	 * 查询地图商家信息
	 * @param mTargetLatLng
	 */
	public void requestMapShopInfo(final int shopId){
		final ProgressDialog dialog = ProgressDialog.show(this, "", "正在获取商家信息...");
		FinalHttp finalHttp = new FinalHttp();
    	finalHttp.configCharset("UTF-8");
    	finalHttp.configTimeout(10*1000);
    	finalHttp.addHeader("Content-Type", "html/text");
    	finalHttp.addHeader("Conection", "Keep-Alive");
    	finalHttp.addHeader("Cache-Control", "no-cache");
    	HashMap<String,String> params = new HashMap<String,String>();
    	params.put("sid", String.valueOf(shopId));
    	params.put("authkey", SystemData.HTTP_KEY);
    	finalHttp.post(SystemHttpURL.URL_SHOP_ALERT_INFO, new AjaxParams(params),new AjaxCallBack<String>(){
    		@Override
    		public void onFailure(Throwable t, int errorNo, String strMsg) {
    			super.onFailure(t, errorNo, strMsg);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("地图商家弹窗信息----错误信息："+strMsg);
    			Toast.makeText(ServiceMapActivity.this, "网络错误，请重试!", Toast.LENGTH_SHORT).show();
    		}
    		@Override
    		public void onSuccess(String str) {
    			super.onSuccess(str);
    			if(dialog!=null) dialog.dismiss();
    			System.out.println("地图商家弹窗信息----返回信息："+str);		
    			MapShopInfoModel model = new MapShopInfoParser(str).getResponseObject();
    			switch(model.status){
    			case 1:
    				//显示地图标注弹窗
    				ShopMarkerInfoEntry info = new ShopMarkerInfoEntry();
    				info.otherInfo = model.mapShopInfoEntry.shopDescription;
    				info.picUrl = model.mapShopInfoEntry.shopThumb;
    				info.shopAddr = model.mapShopInfoEntry.shopAddress;
    				info.shopCall = model.mapShopInfoEntry.shopPhone;
    				info.shopId = shopId;
    				info.shopName = model.mapShopInfoEntry.shopName;
    				info.shopType = flag;
    				final ShopMarkerInfoDialog dialog = new ShopMarkerInfoDialog(ServiceMapActivity.this, info);
    				dialog.setOnOperClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							switch(v.getId()){
							case R.id.dialog_maker_info_imgClose:
							case R.id.dialog_maker_info_txtBack:
								if(dialog!=null) dialog.dismiss();
								break;
							case R.id.dialog_maker_info_txtViewInfo:
								if(dialog!=null) dialog.dismiss();
								//页面转场，跳转至商家详细界面
								Intent intent = new Intent(ServiceMapActivity.this,ShopDetailActivity.class);
								intent.putExtra("shopId", shopId);
								intent.putExtra("flag", flag);
								startActivity(intent);
								overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
								break;
							}
						}
					});
    				dialog.show();
    				break;
    			case 0:
    				Toast.makeText(ServiceMapActivity.this, model.msg, Toast.LENGTH_SHORT).show();
    				break;
    			}
     		}
    	});
	}
    
    @Override  
    protected void onDestroy() {  
        super.onDestroy();  
        mMapView.onDestroy();  
        if(mLocationClient!=null && mLocationClient.isStarted())
        	mLocationClient.stop();
    }  
    
    @Override  
    protected void onResume() {  
        super.onResume();  
        mMapView.onResume();  
        if(mLocationClient!=null && !mLocationClient.isStarted())
        	mLocationClient.start();
    }  
    
    @Override  
    protected void onPause() {  
        super.onPause();  
        mMapView.onPause();  
        if(mLocationClient!=null && mLocationClient.isStarted())
        	mLocationClient.stop();
    }
}
